<template>
  <section>
    <el-row>
      <draggable :list="list" v-bind="$attrs">
        <el-col v-for="(item, i) in list" :key="i" :span="6">
          <section class="v-img-item">
            <el-image v-if="item.link === ''" :src="item.coverImg" fit="contain" @click="setPic(i, item)">
              <div slot="error" class="image-slot" @click="setPic(i, item)">
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
            <video v-else :src="item.link" @click="setPic(i, item)" />
            <section class="del-img" @click="delImg4list(i)">
              <img src="./delete.png" alt="">
            </section>
          </section>
        </el-col>
      </draggable>
      <el-col :span="6">
        <section class="add-img" @click="addImg">
          <i class="el-icon-plus" />
        </section>
      </el-col>
    </el-row>

    <!--设置视频内容-->
    <el-dialog
      v-if="linkFlag"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="visible"
      title="设置视频"
      center
      :before-close="
        () => {
          visible = false
        }
      "
    >
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
        style="max-height: 500px; overflow-y: auto"
        :rules="rules"
      >
        <el-form-item label="视频来源">
          <el-radio-group v-model="form.source" @change="sourceChange">
            <el-radio :label="1">外部链接</el-radio>
            <el-radio :label="2">视频库选取</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="form.source === 2">
          <el-form-item label="视频" prop="coverImg">
            <template>
              <div class="form-uploader" @click="setFormPic">
                <el-image :src="form.coverImg">
                  <div slot="error" class="image-slot my-slot">
                    <template>
                      <div class="icon-wrap">
                        <i
                          class="el-icon-video-camera-solid"
                          style="font-size: 28px"
                        />
                      </div>
                    </template>
                  </div>
                </el-image>
              </div>
            </template>
          </el-form-item>
        </div>

        <!-- <el-form-item label="跳转链接">
          <el-link type="primary" @click="handleLink">
            {{ form.link && form.link.name ? form.link.name : '选择链接' }}
          </el-link>
          <span v-if="form.link && form.link.name" @click="delLink">
            <i style="vertical-align:middle;" class="el-icon-delete" />
          </span>
        </el-form-item> -->
        <div v-if="form.source === 1">
          <el-form-item label="链接地址" prop="link">
            <el-input v-model="form.link" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px"
          @click="visible = false"
        >关 闭</el-button>
        <el-button
          type="primary"
          style="padding: 8px 30px"
          @click="handleSubmit"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!--    从视频库中选择-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      custom-class="live-dialog"
      :visible.sync="showPic"
      title="选择视频"
      width="1200px"
      center
    >
      <library @select="handleChoose" />
      <div slot="footer" class="dialog-footer">
        <el-button
          type="default"
          style="padding: 10px 30px"
          @click="showPic = false"
        >取 消</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import draggable from 'vuedraggable'
import library from './library'
import { getToken } from '@/utils/auth'
import { randomStringForId } from '@/utils'
export default {
  name: 'VImgData',
  components: { draggable, library },
  inject: ['focusId', 'pageVar', 'focusName', 'getListItemInfo'],
  props: {
    option: {
      type: Object,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: {}
    }
  },
  data() {
    return {
      showPic: false,
      list: [],
      index: 0,
      visible: false,
      form: {
        source: 1,
        videoId: '',
        coverImg: '',
        link: '',
        id: randomStringForId(8)
      },
      // title: '',
      // subTitle: '',
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        link: [{ required: true, message: '请输入外部链接', trigger: 'blur' }],
        coverImg: [{ required: true, message: '请设置视频', trigger: 'blur' }]
      },
      upload: {
        headers: {
          token: getToken()
        },
        action: `${process.env.VUE_APP_BASE_API}files/upload`,
        result: '',
        loading: false
      },
      result: '',
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: -1, // 1视频 2视频 3附件
        accept: '',
        fileType: '',
        fileIndex: 0,
        isOss: !!sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG')
      },
      fileViewId: '',
      linkFlag: true,
      fields: []
    }
  },
  created() {
    if (this.option.value !== '') {
      try {
        this.list = this.option.value || []
      } catch (e) {
        console.log(e)
      }
    }
    if (this.option.field !== undefined) {
      this.setForm()
    }
  },
  methods: {
    delLink() {
      const obj = Object.assign({}, this.form)
      obj.link = ''
      this.$set(this, 'form', obj)
    },
    getValue() {
      const obj = {
        [this.option.portName]: {
          code: '200'
        }
      }
      obj[this.option.portName]['data'] = this.list
      return obj
    },
    setValue(k) {
      // this.$set(this, 'list', k)
    },
    setForm() {
      const fields = this.option.field
      this.fields = fields
      fields.forEach((i) => {
        if (this.form[i.param] === undefined) {
          this.form[i.param] = ''
        }
      })
    },
    getLinkValue() {
      return this.form.link || ''
    },
    async handleLink() {
      this.linkFlag = false
      const { default: DialogLinks } = await import(
				'@/components/CustomPage/pagemaker/links'
			)
      this.$modal.show(
        DialogLinks,
        {
          title: '选择链接',
          type: '',
          compVar: this.getListItemInfo(this.focusName())?.componentVariable
            ? JSON.parse(
              this.getListItemInfo(this.focusName()).componentVariable
            )
            : [],
          pageVar: this.pageVar(),
          fn: this.linkcomit,
          cn: this.closeLink,
          upValue: this.getLinkValue() === '' ? {} : this.getLinkValue()
        },
        {
          width: 800,
          height: 'auto',
          clickToClose: false
        }
      )
    },

    closeLink() {
      this.linkFlag = true
      this.$modal.hideAll()
      return true
    },

    linkcomit(type, name, link, params) {
      this.linkFlag = true
      this.form.link = Object.assign({}, { type, name, link, params })
    },
    setFormPic() {
      if (this.form.source === 1) {
        this.uploadFile.showUpload = 2
      } else {
        this.showPic = true
      }
    },
    sourceChange(e) {
      this.showPic = e === 2
    },
    handleChoose(obj) {
      if (obj.subjectImg !== undefined && obj.subjectImg !== '') {
        this.form.coverImg = obj.subjectImgUrl
      } else {
        this.form.coverImg = this.uploadFile.view + obj.videoId
      }
      this.form.videoId = obj.courseId
      this.showPic = false
    },
    beforeupload(file) {
      const _this = this
      const { maxSize } = this
      const size = file.size / 1024 / 1024 <= maxSize
      if (!size) {
        this.$confirm(`文件大小超过${maxSize}MB限制`, '提示', {
          confirmButtonText: '重新上传',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false
        }).then(() => {
          _this.$refs.upload.$children[0].handleClick()
        })
      }
      if (size) {
        this.upload.loading = true
      }
      return size
    },
    delImg4list(i) {
      this.list.splice(i, 1)
    },
    addImg() {
      this.list.push({
        // id: this.list.length,
        videoId: '',
        imgUrl: '',
        title: '',
        subTitle: '',
        id: randomStringForId(8)
      })
    },
    setPic(i, item) {
      if (item.videoId || item.link) {
        this.form = Object.assign({}, item)
      } else {
        this.form = {
          source: 1,
          videoId: '',
          coverImg: '',
          link: '',
          id: randomStringForId(8)
        }
      }
      this.visible = true
      this.index = i
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.list[this.index] = this.form
          this.visible = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/var.scss';
.v-img-item {
	position: relative;
	background: #fafafa;
	height: 80px;
	margin: 10px;
  video{
    width: 100%;
    height: 100%;
  }
	.del-img {
		position: absolute;
		width: 20px;
		height: 20px;
		top: 0;
		right: 0;
		> img {
			height: 100%;
			width: 100%;
		}
	}
}
.add-img {
	background: #fafafa;
	height: 80px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 10px;
}
/deep/ .form-uploader {
	position: relative;
	.my-slot {
		display: block;
		padding-left: 50px;
	}
	.el-icon-delete {
		//position: absolute;
		//right: -20px;
		//top: 4px;
		float: right;
		&:hover {
			color: $mainColor;
			transform: scale(1.5);
		}
	}
	.el-image {
		width: 100px;
		height: auto;
	}
}
</style>
